package com.asiainfo.dacp.datastash.worker.executor.adapter.datax;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.asiainfo.dacp.datastash.common.WorkerExecutor;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.Constant;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.model.domain.JobId;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.translate.JdbcTranslate;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.translate.JobTranslate;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.ConfigUtils;
import com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils.Configuration;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.io.Files;

import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * DataX 的 Worker的执行器类
 *
 * @author MeiKefu
 * @date 2017-10-31
 */
public class DataxWorkerExecutor implements WorkerExecutor{
	private static final Logger LOG = LoggerFactory.getLogger(DataxWorkerExecutor.class);

	public static void argumentParser(String[] args){
		ArgumentParser parser = ArgumentParsers.newArgumentParser("datax-worker", true);
		parser.addArgument("p").metavar("JsonPara").required(true);
		try{
			Namespace res  = parser.parseArgs(args);
			String jsonp = res.getString("p"); 
			Constant.GLOBAL_CONF = Configuration.from(jsonp);
			LOG.info("\n入参 : {}" , Constant.GLOBAL_CONF.beautify());  
		} catch (ArgumentParserException e) {
			parser.handleError(e);
			System.exit(-1);
		} catch (Exception e){
			LOG.error("获取入参失败 .", e);
			System.exit(-1);
		}
	}
	
	public static int entry(final String[] args) throws Throwable { 
		argumentParser(args); 
	
		String unitid = null;
		if(Constant.GLOBAL_CONF != null){
			unitid = Constant.GLOBAL_CONF.getString(Constant.DATAX_ENTRY_PARAM_UNITID);
		}else{
			unitid = System.getProperty(Constant.DATAX_ENTRY_PARAM_UNITID);
		}
		Preconditions.checkNotNull(unitid, "接口单元号未获取 .");
 		LOG.info("接口单元号 : {}" , unitid);  
 		
 		//spring -
 		ApplicationContext context = new FileSystemXmlApplicationContext(new String[]{"classpath:conf/spring/*.xml","conf/spring/*.xml"});
 		JobTranslate JdbcTranslate = context.getBean(JdbcTranslate.class);

		DataxTranslater translator = new DataxTranslater(JdbcTranslate);
		String content = translator.getJsonStr(translator.jobInfo(new JobId(unitid)));
		
		String genFile = genFile(unitid, content,".json");
		
		//int execByProcess = 0;
		int execByProcess = execByProcess(genFile);
		return execByProcess;
	}
	public static String genFile(String unitid, String content,String suffix) throws IOException {
		SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATAX_JSON_FILE_NAME_DATE_FMT);

		String path = ConfigUtils.getCfg(Constant.DATAX_JSON_FILE_PATH);
		String fileName = unitid + sdf.format(new Date()) + UUID.randomUUID().toString();
		File file = new File(path + File.separator + fileName+suffix);
		LOG.info(String.format("构建DATAX json file :[%s] .", file.getAbsolutePath()));
		Files.write(content, file, Charset.defaultCharset());
		return file.getAbsolutePath();
	}

	public static int execByProcess(String fileName) throws Exception {
		String path = ConfigUtils.getCfg(Constant.DATAX_EXECUTE_PATH);
		LOG.info("DATAX程序执行脚本路径:［{}］.", path);
		String joinedCommand = Joiner.on(' ').join(new String[]{ path, fileName });
		LOG.info("程序执行［{}］.", joinedCommand);
		CommandLine cl = CommandLine.parse(path); 
		cl.addArgument(fileName);
		Executor exec = new DefaultExecutor();
		return exec.execute(cl);
	}

	// 获得下发任务内容

	// 适配成通用处理格式 
	// 参数填充替换－外部参数和内部参数映射关系
	// 1.根据reader／writer的类型获取不同plugin的模版parameter
	// 2.读取映射关系配置文件（可选）获取参数映射关系
	// 3.读取通用模版，填充参数
	// 生成配置文件

	// 调用程序处理
 
	public static void main(String[] args) throws Throwable {
		DataxWorkerExecutor.entry(args);
	}
	
	
    public void execute(){
        System.out.println("datax execute");
    }

	@Override
	public int execute(String[] args) {
		try {
			/**
			URLClassLoader classLoader = (URLClassLoader) this.getClass().getClassLoader();
			for(URL url: classLoader.getURLs())
				System.out.println(url);
				*/

 			return DataxWorkerExecutor.entry(args);
		} catch (Throwable e) {
			e.printStackTrace();
			return -1;
		}
	}

}